Script ExecuteSelect
(stmt, v)

Connection@qpg x;
Result@qpg y;
I4 ret;
String s;

ret = MakeConnection@@qpg(x, "host=172.16.98.243 port=5432 dbname=pg user=rtd password=postgres");
if (ret)
{
	PrintLn("[PG] Error in MakeConnection");
	return -1;
}

ret = Execute@@qpg(x, y, stmt);
if (ret)
{
	PrintLn("ExecuteSelect error ", ret, "\x0A", ifexp(ErrorMessage@@qpg(x, s))("Unknown error")(s));
	return -1;
}

ret = ResultStatus@@qpg(y);
if (ret != 2)
{
	PrintLn("Error code is ", ret, ", ", ErrorMessage@@qpg(x, s));
	
	PrintLn(s);
	return -1;
}

return FetchAll(y, v);

EndScript

Script Execute
(stmt)
Connection@qpg x;
Result@qpg y;
String s;
I4 ret;

ret = MakeConnection@@qpg(x, "host=172.16.98.243 port=5432 dbname=pg user=rtd password=postgres");
if (ret)
{
	PrintLn("[PG] Error in MakeConnection");
	return -1;
}

ret = Execute@@qpg(x, y, stmt);
if (ret)
{
	PrintLn("Execute error ", ret, "\x0A", ErrorMessage@@qpg(x, s));
	return -1;
}

ret = ResultStatus@@qpg(y);
//PrintLn("ResultStatus is ", ret);
if (ret != 1)
{
	PrintLn("Error code is ", ret, ", ", ErrorMessage@@qpg(x, s));
	PrintLn(s);
	PrintLn(stmt);
	return -1;
}

return 0;
EndScript

Script CStatement
U4 type = 0;
String t1, t2;

Script Clear
t1 = "";
t2 = "";
EndScript

Script SimpleDelete
(tname, col, val)
String tmp;
return StrAssign(tmp, "DELETE FROM ", tname, " WHERE ", col, " = '", val, "'");
EndScript

Script SimpleSelect
(tname, col, cond)
String tmp, tmp2;
return StrAssign(tmp, "SELECT ", col, " FROM ", tname, ifexp(GetCount(Parameter) == 3 && StrLen(cond))(StrAssign(tmp2, " WHERE ", cond))(""));
EndScript

Script Insert
(col, value)
if (StrLen(t1))
{
	StrAppend(t1, ",");
}
StrAppend(t1, col);

if (StrLen(t2))
{
	StrAppend(t2, ",");
}

StrAppend(t2, "'", value, "'");

EndScript

Script InsertStr
(col, value)
if (StrLen(value))
{
	Insert(col, value);
}
EndScript

Script GetInsert
(tname)
String tmp;
return StrAssign(tmp, "INSERT INTO ", tname, " (", t1, ") VALUES (", t2, ")");
EndScript

Script Update
(col, value)
if (StrLen(t1))
{
	StrAppend(t1, ",");
}
StrAppend(t1, col, "='", value, "'");
EndScript

Script UpdateStr
(col, value)
if (StrLen(value))
{
	Update(col, value);
	
}
EndScript

Script GetUpdate
(tname, cond)
String tmp;
return StrAssign(tmp, "UPDATE ", tname, " SET ", t1, " WHERE ", cond);
EndScript

EndScript

Script FetchAll
(data, v)

Reference pv;
VectorClear(v);
String s;
U4 row, col;
U4 loop, loop2;

col = GetColumnCount@@qpg(data);
row = GetRowCount@@qpg(data);

loop = 0;
while (loop < row)
{
	VectorPushExP(v, "Vector", pv);
	loop2 = 0;
	while (loop2 < col)
	{
		if (GetData@@qpg(data, loop, loop2, s))
		{
			AppLog("[", ScriptName(), "] Failed to get data at ", row, ", ", col);
			return -1;
		}
		VectorPush(pv, s);
		Inc(loop2);
	}
	Inc(loop);
}
return 0;
EndScript
